//
//  CZMessionCenterViewController.m
//  nsj_iOS
//
//  Created by apple on 2016/12/7.
//  Copyright © 2016年 GCZ. All rights reserved.
//

#import "CZMessionCenterViewController.h"
#import "CZCMessionCenterNewsTableViewCell.h"
#import "CZMessionCenterTableViewCell.h"
#import "CZDoujinListViewController.h"
#import "CZDoujinCenterViewController.h"
#import "CZBaseTabBarController.h"
#import "CZLoginView.h"
#import "CZPasswordLoginView.h"
#import "CZAlbumModel.h"
#import "CZWebNoticeViewController.h"

static NSString *const cz_table_cell = @"cz_table_cell";
static NSString *const cz_collection_cell = @"cz_collection_cell";
#define USER_ICON_WIDTH Main_Screen_Width * 0.2

@interface CZMessionCenterViewController () <UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, copy) NSArray<NSDictionary *> *albumArray;
@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, copy) NSArray<NSDictionary *> *newsArray;
@property (nonatomic, strong) LGRefreshView *refreshView;

@end

@implementation CZMessionCenterViewController

- (NSArray *)albumArray {
    if (!_albumArray) {
        if (_albumArray) {
            _albumArray = [[NSArray alloc] init];
        }
    }
    return _albumArray;
}
- (NSArray *)newsArray {
    if (!_newsArray) {
        if (_newsArray) {
            _newsArray = [[NSArray alloc] init];
        }
    }
    return _newsArray;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationController.delegate = self;
    [(UIView*)[self.navigationController.navigationBar.subviews objectAtIndex:0] setAlpha:1.f];
    UITableView *mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, -20, Main_Screen_Width, Main_Screen_Height + 20) style:(UITableViewStyleGrouped)];
    mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:mainTableView];
    mainTableView.delegate = self;
    mainTableView.dataSource = self;
    mainTableView.estimatedRowHeight = 110;
    mainTableView.rowHeight = UITableViewAutomaticDimension;
//    mainTableView.bounces = NO;
    _mainTableView = mainTableView;
    [mainTableView registerClass:[CZMessionCenterTableViewCell class] forCellReuseIdentifier:cz_collection_cell];
    [mainTableView registerNib:[UINib nibWithNibName:@"CZCMessionCenterNewsTableViewCell" bundle:nil] forCellReuseIdentifier:cz_table_cell];
    
    _refreshView = [LGRefreshView refreshViewWithScrollView:mainTableView
                                             refreshHandler:^(LGRefreshView *refreshView){
                                                 [self getData];
                                             }];
    _refreshView.center = CGPointMake(Main_Screen_Width / 2, _refreshView.center.y);
    _refreshView.tintColor = ThemeColor;
    _refreshView.backgroundColor = [UIColor clearColor];
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Width * 0.56)];
    CZGestureImageView *imageView = [[CZGestureImageView alloc] initWithFrame:CGRectMake(-1, - 1, Main_Screen_Width + 2, Main_Screen_Width * 0.56 + 2)];
    imageView.image = [UIImage imageNamed:@"man_banner"];
    [headerView addSubview:imageView];
    mainTableView.tableHeaderView = headerView;
//    [self getAlbumData];
//    [self postNewsData];
    [self getData];
}
- (void)setUserIconImage {
    if ([[NSUserDefaults standardUserDefaults] objectForKey:User_Logo]) {
        self.userIcon.yy_imageURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:User_Logo]];
    } else {
        self.userIcon.image = [UIImage imageNamed:@"logo"];
    }
}
- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
    [super viewWillAppear:animated];
}


- (void)getData {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        dispatch_group_t downloadGroup = dispatch_group_create();
        dispatch_group_enter(downloadGroup);
        dispatch_group_enter(downloadGroup);
        NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/doujin/recommended-doujin",APP_HOST];
        [GCZAFNetWorking GET:urlString success:^(NSDictionary *response) {
            if ([response[@"code"] isEqualToString:@"200"]) {
                NSArray *array = response[@"result"];
                self.albumArray = array;
            }
            dispatch_group_leave(downloadGroup);
        } failure:^(NSURLSessionDataTask *operation, NSError *error) {
            dispatch_group_leave(downloadGroup);
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }];
        
        NSString *newsURL = [NSString stringWithFormat:@"%@/api/web/index.php/v1/article/index",APP_HOST];
        [GCZAFNetWorking POST:newsURL params:@{@"article_type" : @1, @"limit" : @3} success:^(NSDictionary *response) {
            if ([response[@"code"] isEqualToString: @"200"]) {
                self.newsArray = response[@"result"];
            }
            dispatch_group_leave(downloadGroup);
        } failure:^(NSURLSessionDataTask *operation, NSError *error) {
            dispatch_group_leave(downloadGroup);
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
        }];
        
        dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            [_refreshView endRefreshing];
            [self.mainTableView reloadData];
        });
    });
}
- (void)getAlbumData {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/doujin/recommended-doujin",APP_HOST];
    [GCZAFNetWorking GET:urlString success:^(NSDictionary *response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            NSArray *array = response[@"result"];
            self.albumArray = array;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.mainTableView reloadData];
            });
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        
    }];
}

- (void)postNewsData {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/article/index",APP_HOST];
    
    [GCZAFNetWorking POST:urlString params:@{@"article_type" : @1, @"limit" : @3} success:^(NSDictionary *response) {
        if ([response[@"code"] isEqualToString: @"200"]) {
            self.newsArray = response[@"result"];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.mainTableView reloadData];
            });
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section == 0 ? 1 : self.newsArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return (Main_Screen_Width - 10) / 2 * 0.6 * 3 + 30;
    } else {
        return 108;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Width * 0.5 * 0.237)];
    CZGestureImageView *imageView = [[CZGestureImageView alloc] initWithFrame:CGRectMake(Main_Screen_Width / 2 - Main_Screen_Width * 0.25, 10, Main_Screen_Width * 0.5, Main_Screen_Width * 0.5 * 0.237)];
    imageView.image =  [UIImage imageNamed:(section == 0 ? @"share_gap" : @"news_gap")];
    [headerView addSubview:imageView];
    headerView.backgroundColor = GLOBAL_BACKGROUND_COLOR;
    if (section == 0) {
        CZGestureImageView *userIcon = [[CZGestureImageView alloc] init];
        self.userIcon = userIcon;
        [self setUserIconImage];
        userIcon.size = CGSizeMake(USER_ICON_WIDTH,USER_ICON_WIDTH);
        userIcon.centerY = headerView.top;
        userIcon.right = self.mainTableView.right - 15;
        userIcon.backgroundColor = [UIColor whiteColor];
        userIcon.layer.cornerRadius = USER_ICON_WIDTH / 2;
        userIcon.layer.borderWidth = 1.f;
        userIcon.layer.borderColor = [UIColor whiteColor].CGColor;
        userIcon.clipsToBounds = YES;
        
        UIView *shadowView = [[UIView alloc]initWithFrame:userIcon.frame];
        userIcon.frame = CGRectMake(0, 0, USER_ICON_WIDTH, USER_ICON_WIDTH);
        [self.view addSubview:shadowView];
        shadowView.layer.shadowColor = [UIColor blackColor].CGColor;
        shadowView.layer.shadowOffset = CGSizeMake(0, 2);
        shadowView.layer.shadowOpacity = 0.3;
        shadowView.layer.shadowRadius = 2.0;
        shadowView.layer.cornerRadius = USER_ICON_WIDTH / 2;
        shadowView.clipsToBounds = NO;
        [shadowView addSubview:userIcon];
        [headerView addSubview:shadowView];
    }
    return headerView;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return Main_Screen_Width * 0.5 * 0.237 + 20;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Main_Screen_Width, Main_Screen_Width * 0.09)];
    
    CZGestureImageView *imageView = [[CZGestureImageView alloc] initWithFrame:CGRectMake(-1, 10, Main_Screen_Width + 2, Main_Screen_Width * 0.09)];
    imageView.image =  [UIImage imageNamed:@"more_back"];
    UILabel *title = [[UILabel alloc] initWithFrame:footView.bounds];   
    title.font = [UIFont fontWithName:@"Helvetica-Bold" size:16];
    title.textColor = [UIColor whiteColor];
    title.text = section == 0 ? @"更多作品" : @"更多新闻";
    title.textAlignment = NSTextAlignmentCenter;
    title.top = footView.top + 10;
    [footView addSubview:imageView];
    [footView addSubview:title];

    footView.backgroundColor = GLOBAL_BACKGROUND_COLOR;
    if (section == 0) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doujinShare)];
        [footView addGestureRecognizer:tap];
        footView.userInteractionEnabled = YES;
    } else {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreNews)];
        [footView addGestureRecognizer:tap];
        footView.userInteractionEnabled = YES;
    }
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return Main_Screen_Width * 0.09 + 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        CZMessionCenterTableViewCell *cell = (CZMessionCenterTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cz_collection_cell];
        cell.homeVC = self;
        cell.albumArray = self.albumArray;
        [cell.collectionView reloadData];
        return cell;
    } else {
        CZCMessionCenterNewsTableViewCell *cell = (CZCMessionCenterNewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cz_table_cell];
        NSDictionary *dic = self.newsArray[indexPath.row];
        cell.newsTitleLabel.text = dic[@"title"];
        cell.abstractLabel.text = dic[@"article_abstract"];
        cell.newsIcon.yy_imageURL = [NSURL URLWithString:dic[@"cover_pic"]];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        CZWebNoticeViewController *webVC = [[CZWebNoticeViewController alloc] init];
        NSDictionary *dic = self.newsArray[indexPath.row];
        webVC.articleID = dic[@"article_id"];
        webVC.type = @"公告新闻";
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

- (void)drumpToWebView {

}

- (void)doujinShare {
    CZDoujinCenterViewController *doujinVC = [[CZDoujinCenterViewController alloc] init];
    [self.navigationController pushViewController:doujinVC animated:YES];
}

- (void)moreNews {
    CZBaseTabBarController *rootVC = (CZBaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    rootVC.selectedIndex = 3;
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
